﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BoutiquePOS.DAL.DAO;
using BoutiquePOS.DAL.Gateway;
using BoutiquePOS.Manager;

namespace BoutiquePOS.UI.UserUI
{
    public partial class SalesEntry : System.Web.UI.Page
    {

        ProductCategoryManager productCategoryManager = new ProductCategoryManager();
        List<ProductCategory> productCategories = new List<ProductCategory>();
        SalesManager salesManager = new SalesManager();
        List<SalesDtls> salesDetailsList = new List<SalesDtls>();
        private List<SalesDtls> salesDtlses = null;
        public string SuggestionList = "";
        Product product = new Product();
        string productName = "";
        decimal tradePrice = 0;
        decimal mrp = 0;
        decimal totalMrp = 0;
        int qty = 0;
        double discountPer = 0;
        decimal discountAmt = 0;
        int freeQty = 0;
        decimal totalMRPSum = 0;
        decimal paidAmount = 0;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                ProductCategoryDDl();
                int categoryId = Convert.ToInt32(productCategoryDDList.SelectedValue);
                SuggestionList = salesManager.GetProductNameAutoCompleteData(categoryId);   
                Session["ProductList"] = salesDetailsList;                              

                messageLebel.Text = "";
                NextId();

                string dateAsString = DateTime.Now.ToString("yyyy-MM-dd");
                salesDateTextBox.Value = dateAsString;
<<<<<<< .mine
                txtCustomerID.Text = salesManager.AutoCustomerCode();

=======
>>>>>>> .r17
            }
        }

        private void ProductCategoryDDl()
        {
            productCategories = productCategoryManager.GetAllProductCategory();
            productCategoryDDList.DataTextField = "CategoryName";
            productCategoryDDList.DataValueField = "CategoryId";
            productCategoryDDList.DataSource = productCategories;
            productCategoryDDList.DataBind();
            //productCategoryDDList.Items.Insert(0, "---Choose Any---");
        }

        private void NextId()
        {
            string yearAndMonth = GetYearAndMonth();
            string salesNo = salesManager.NextID(yearAndMonth);
            salesNoTextBox.Value = salesNo;
        }

        private static string GetYearAndMonth()
        {
            DateTime dateTime = DateTime.Now;
            int year = dateTime.Year;
            int month = dateTime.Month;
            string finalMonth = "";
            if (month < 10)
            {
                finalMonth = "0" + month;
            }
            else
            {
                finalMonth = month.ToString();
            }
            return year + finalMonth;
        }

        protected void productCategoryDDList_SelectedIndexChanged(object sender, EventArgs e)
        {
            int categoryId = Convert.ToInt32(productCategoryDDList.SelectedValue);
            SuggestionList = salesManager.GetProductNameAutoCompleteData(categoryId);
        }

        protected void qtyTextBox_TextChanged(object sender, EventArgs e)
        {
            CalculateNetAmount(0);
        }

        private void CalculateNetAmount(decimal dicountPercentage)
        {
            try
            {
                ProductManager productManager = new ProductManager();
                int formId = Convert.ToInt32(productCategoryDDList.SelectedValue);
                string productName = productNameTextBox.Value;
                Product product = null;
                product = productManager.GetUnitPrice(formId, productName);
                tradePriceTextBox.Value = product.TradePrice.ToString();
                mrpTextBox.Value = product.Mrp.ToString();
                decimal totalMrp = Convert.ToDecimal(qtyTextBox.Text) * Convert.ToDecimal(mrpTextBox.Value);
                totalMRPTextBox.Value = totalMrp.ToString();
                decimal discountAmount = 0;
                if (dicountPercentage <= 0)
                {
                    discountAmount = 0;
                }
                else if (dicountPercentage > 0)
                {
                    discountAmount = totalMrp * ((dicountPercentage) / (100));
                }
                discountAmtTextBox.Value = discountAmount.ToString();
            }
            catch (Exception)
            {
                throw;
            }
        }

        protected void discountPercentTextBox_TextChanged(object sender, EventArgs e)
        {
            decimal discountPercentage = Convert.ToDecimal(discountPercentTextBox.Text);
            CalculateNetAmount(discountPercentage);
        }

        protected void AddtoGridView_Click(object sender, EventArgs e)
        {
            try
            {
                ProductManager productManager = new ProductManager();
                SalesDtls salesDtls = new SalesDtls();
                decimal totalNetAmount = 0;
                productName = productNameTextBox.Value;
                qty = Convert.ToInt32(qtyTextBox.Text);
                freeQty = Convert.ToInt32(freeQtyTextBox.Value);
                tradePrice = Convert.ToDecimal(tradePriceTextBox.Value);
                mrp = Convert.ToDecimal(mrpTextBox.Value);
                totalMrp = Convert.ToDecimal(totalMRPTextBox.Value);
                discountPer = Convert.ToDouble(discountPercentTextBox.Text);
                discountAmt = Convert.ToDecimal(discountAmtTextBox.Value);

                Product aproduct = productManager.GetUnitPrice(Convert.ToInt32(productCategoryDDList.SelectedValue), productName);
                salesDtls.AProduct = aproduct;
                salesDtls.AProduct.ProductBrandName = productName;
                salesDtls.AProduct.ProductId = aproduct.ProductId;
                salesDtls.ProductId = aproduct.ProductId;
                salesDtls.ProductName = aproduct.ProductBrandName;
                salesDtls.SalesQty = qty;
                salesDtls.SalesFreeQty = freeQty;
                salesDtls.TradePrice = tradePrice;
                salesDtls.Mrp = mrp;
                salesDtls.TotalMrp = totalMrp;
                salesDtls.DiscountPer = discountPer;
                salesDtls.DiscountAmt = discountAmt;
                salesDetailsList = (List<SalesDtls>)Session["ProductList"];
                salesDetailsList.Add(salesDtls);
                salesGridView.DataSource = salesDetailsList;
                salesGridView.DataBind();

                int formId = Convert.ToInt32(productCategoryDDList.SelectedValue);      //last change
                SuggestionList = salesManager.GetProductNameAutoCompleteData(formId);   //last change

                foreach (SalesDtls salesDtlse in salesDetailsList)
                {
                    totalNetAmount += salesDtlse.TotalMrp - salesDtlse.DiscountAmt;
                }
                salesGridView.DataBind();
                totalNetAmtTextBox.Value = totalNetAmount.ToString();

                gvClear();

                if (selectPaymentMode.Value == "1")
                {
                    paidAmountTextBox.Text = totalNetAmtTextBox.Value;
                    dueAmtTextBox.Value = "0";
                }
                else
                {
                    paidAmountTextBox.Text = "";
                }
            }
            catch (Exception)
            {
                throw;
            }
        }

        protected void paidAmtTextBox_TextChanged(object sender, EventArgs e)
        {
            try
            {
                decimal dueAmount = Convert.ToDecimal(totalNetAmtTextBox.Value) - Convert.ToDecimal(paidAmountTextBox.Text);
                dueAmtTextBox.Value = dueAmount.ToString();
            }
            catch (Exception)
            {
                throw new Exception("");
            }
        }

        protected void SaveButton(object sender, EventArgs e)
        {
            try
            {
                SalesGateway salesGateway = new SalesGateway();

                //---------Sales Info (Single Row Insert)-----//              
                string salesNo = salesNoTextBox.Value;
                string salesDate = salesDateTextBox.Value;

                Sales asales = new Sales();
                asales.SalesNo = salesNo;
                asales.SalesDate = salesDate;

                Customer aCustomer = new Customer();
<<<<<<< .mine
                string customerCode = customerIdTextBox.Text;
                int customerId = salesManager.GetCustomerId(customerCode);
                aCustomer.CustomerId = customerId;
=======
                string customerId = customerIdTextBox.Value;
>>>>>>> .r17
                asales.ACustomer = aCustomer;
<<<<<<< .mine
=======
                asales.ACustomer.CustomerId = customerId;

>>>>>>> .r17
                asales.TotalNetAmount = Convert.ToDecimal(totalNetAmtTextBox.Value);
                salesGateway.SaveaSales(asales);
                int id = salesGateway.ReturnSalesId(asales.SalesNo);

                //------Customer Payment------------//
                CustomerPayment aCustomerPayment = new CustomerPayment();
                asales.SalesId = id;
                aCustomerPayment.ASales = asales;
                aCustomerPayment.PaymentDate = salesDateTextBox.Value;
                aCustomerPayment.PaidAmount = Convert.ToDecimal(paidAmountTextBox.Text);
                salesGateway.SaveCustomerPayment(aCustomerPayment);

                //---------Sales Details Insert (Product)--------------//
                SalesDtls aSalesDtls = new SalesDtls();
                aSalesDtls.SalesId = id;
                int paymentMode = Convert.ToInt32(selectPaymentMode.Value);

                List<SalesDtls> salesDtlses = (List<SalesDtls>)Session["ProductList"];
                foreach (SalesDtls salesDtls in salesDtlses)
                {
                    salesDtls.SalesId = id;
                    salesDtls.PaymentMode = paymentMode;
                }
                salesGateway.SaveSales(salesDtlses);  //direct gateway

                salesGridView.DataSource = null;
                salesGridView.DataBind();

                Clear();
                NextId();
                messageLebel.Text = "Save Successfully";
            }
            catch (Exception)
            {
                messageLebel.Text = "Incorrect Information.";
            }
        }

        private void gvClear()
        {
            //productNameTextBox.Value = "";
            //qtyTextBox.Text = "";
            //tradePriceTextBox.Value = "";
            //discountPercentTextBox.Text = "";
            //mrpTextBox.Value = "";
            //totalMRPTextBox.Value = "";
            //discountPercentTextBox.Text = "";
            //discountAmtTextBox.Value = "";
            //freeQtyTextBox.Value = "";
        }

        private void Clear()
        {
            //productNameTextBox.Value = "";
            //qtyTextBox.Text = "";
            //tradePriceTextBox.Value = "";
            //discountPercentTextBox.Text = "";
            //mrpTextBox.Value = "";
            //totalMRPTextBox.Value = "";
            //discountPercentTextBox.Text = "";
            //discountAmtTextBox.Value = "";
            //freeQtyTextBox.Value = "";
        }

        protected void CloseButton(object sender, EventArgs e)
        {
            Response.Redirect("~/Login.aspx");
        }
        protected void ClearButton(object sender, EventArgs e)
        {
            clear();
        }
        private void clear()
        {
            salesNoTextBox.Value = "";
        }
<<<<<<< .mine
        public void SaveCustomer(object sender, EventArgs e)
        {
            try
            {
                SalesManager manager = new SalesManager();
                Customer aCustomer = new Customer();
                aCustomer.CustomerCode = txtCustomerID.Text;
                aCustomer.CustomerFullName = txtCustomerFullname.Text;
                aCustomer.CustomerPhone = txtCustomerPhone.Text;
                aCustomer.CustomerEmail = txtCustomerEmail.Text;
                manager.SaveCustomer(aCustomer);
                msgCutomerPanel.Text = "Customer Save Successfully";
                msgCutomerPanel.ForeColor = Color.Green;
                customerIdTextBox.Text = txtCustomerID.Text;

            }
            catch (Exception)
            {
=======
>>>>>>> .r17

<<<<<<< .mine
                msgCutomerPanel.Text = "Customer not Save ";
                msgCutomerPanel.ForeColor = Color.Red;
            }

        }

        protected void customerIdTextBox_TextChanged(object sender, EventArgs e)
        {
            try
            {
                messageLebel.Text = "";
                int customerId = salesManager.GetCustomerId(customerIdTextBox.Text);
                if (customerId > 0)
                {

                }
                else
                {
                    messageLebel.Text = "Customer id does not found";
                    messageLebel.ForeColor = Color.Red;
                }

            }
            catch (Exception)
            {



            }
        }
=======
>>>>>>> .r17
    }
}